<template>
  <div style="height: 100%; width: 100%; position: relative">
      <div class="pagetop" :style="'height:' + topheight + 'px;'" style="width: 100%">
          <template>
              <div width="100%">
                  <div style="float: left; width: 100%">
                      <table width="100%">
                          <tr>
                              <td>仪器</td>
                              <td>
                                  <rm-ddl-instrument @change="labinstrumentchange" width="200px" v-model="instrId" defaultflag="1" prgno="LIS514" :clearable="false"></rm-ddl-instrument>
                              </td>

                              <td align="right" width="70%">
                                  <el-button icon="el-icon-search" @click="initialList()" v-has="'PINQUERY'">查询(F8)</el-button>
                                  <el-button icon="el-icon-plus" @click="BtnAdd()" v-has="'PADD'">新增(F2)</el-button>
                                  <el-button icon="el-icon-delete-solid" @click="BtnDel()" v-has="'PDELETE'">删除(F3)</el-button>
                                  <el-button type="primary" icon="el-icon-edit-outline" @click="BtnSave()" v-has="'PMODIFY'">保存(F6)</el-button>
                                  <el-button icon="el-icon-close" @click="BtnExc">退出(E)</el-button>
                              </td>
                          </tr>
                      </table>
                  </div>
              </div>
          </template>
      </div>

      <!-- 上方分隔条 -->
      <div class="xsplit" :style="'top:' + topheight + 'px;'" @mousedown="xtopmousedown"></div>

      <!-- 左边list列表 -->
      <div class="pagecenter" :style="'top:' + (topheight + 5) + 'px;bottom:' + (bottomheight + 5) + 'px;'">
          <div class="middle-center" id="leftGrid" :style="'width:' + rightwidth + 'px;'">
              <vxe-table show-overflow ref="xTable1" height="auto" width="100%" :loading="loading" :select-config="{ reserve: true }" :data.sync="tableData1" border size="mini" :keyboard-config="keyConfig" :mouse-config="{ selected: true }" show-header-overflow highlight-current-row highlight-hover-row resizable stripe :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" @current-change="masterRowChangedEvent">
                  <vxe-table-column type="index" title="NO." width="50"></vxe-table-column>
                  <vxe-table-column field="rpt_itemname" title="项目名称" width="150" sortable header-align="center"> </vxe-table-column>
                  <vxe-table-column field="itemcode_en" title="项目英文名称" width="120" sortable header-align="center"> </vxe-table-column>
                  <vxe-table-column field="rpt_itemcode" title="项目代码" width="100" sortable header-align="center"></vxe-table-column>
              </vxe-table>
          </div>

          <!-- 右边分割条 -->
          <div class="ysplit" :style="'left:' + rightwidth + 'px;'" @mousedown="yleftmousedown"></div>

          <!-- 右边数据展现  -->
          <div class="middle-right" :style="'right:' + leftwidth + 'px;left:' + (rightwidth + 5) + 'px;'">
              <div style="width: 100%; height: 100%">
                  <vxe-table show-overflow ref="xTable2" height="auto" width="100%" :loading="loading" :select-config="{ reserve: true }" :data.sync="tableData2" border size="mini" :keyboard-config="keyConfig" :mouse-config="{ selected: true }" @cell-dblclick="openRule" show-header-overflow highlight-current-row highlight-hover-row resizable stripe :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }">
                      <vxe-table-column field="qcruletype" title="规则大类" width="120" header-align="center" :edit-render="{ type: 'default' }">
                          <template v-slot="{ row }">
                              <el-select v-model="row.qcruletype">
                                  <el-option v-for="item in westgardOption" :key="item.value" :label="item.label" :value="item.value">{{ item.label }}</el-option>
                              </el-select>
                          </template>
                      </vxe-table-column>

                      <vxe-table-column field="qcrule" title="Westgard规则(双击修改)" width="400" header-align="center"></vxe-table-column>
                      <vxe-table-column field="begindt" title="启用日期" width="150" header-align="center" align="center" :formatter="['toDateString', 'yyyy-MM-dd']">
                          <template v-slot="{ row }">
                              <el-date-picker v-model="row.begindt" type="date" placeholder="选择日期" style="width: 100%"></el-date-picker>
                          </template>
                      </vxe-table-column>

                      <vxe-table-column field="stopdt" title="结束日期" width="150" header-align="center" align="center" :formatter="['toDateString', 'yyyy-MM-dd']">
                          <template v-slot="{ row }">
                              <el-date-picker v-model="row.stopdt" type="date" placeholder="选择日期" style="width: 100%"></el-date-picker>
                          </template>
                      </vxe-table-column>
                  </vxe-table>
              </div>
          </div>
      </div>
      <el-dialog width="620px" top="10px" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="选择Westgard质控规则" :visible.sync="qcruleDialogVisible">
          <vxe-table ref="xTable3" height="480" width="100%" :loading="loading" :select-config="{ reserve: true }" :data.sync="tableData3" border size="mini" :keyboard-config="keyConfig" :mouse-config="{ selected: true }" show-header-overflow highlight-current-row highlight-hover-row resizable stripe :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }">
              <vxe-table-column type="selection" width="50" align="center"></vxe-table-column>
              <vxe-table-column field="qcrule" title="质控规则" width="100" align="center"></vxe-table-column>
              <vxe-table-column field="ruleText" title="规则内容" width="400" header-align="center"></vxe-table-column>
          </vxe-table>
          <span slot="footer" class="dialog-footer">
              <el-button style="margin: 0px 10px 0px 5px" icon="el-icon-success" @click="ruleOk()">确定</el-button>
              <el-button style="margin: 0px 10px 0px 5px" icon="el-icon-close" @click="ruleClose()">退出</el-button>
          </span>
      </el-dialog>
  </div>
</template>

<!----------------------------------  代码和显示l的华丽的分割线 ---------------------------------------------->

<script type="text/javascript">
import XEUtils from "xe-utils"; //引入工具类
export default {
  name: "LIS514",
  data() {
      return {
          loading: false,
          dialogTableVisible: false, //弹窗是否打开，默认关闭
          instrId: 0,
          instrName: "",
          rpt_itemcode: "",
          tableData1: [], //左边liist 数据
          tableData2: [], //右边detail的Grid窗口数据
          tableData3: [],
          findRow: 0, //新增时，返回左边list的 row （行数据集合）
          qcruleDialogVisible: false,
          westgardOption: [
              { label: "Westgard", value: 1 },
              { label: "绝对值", value: 2 },
              { label: "百分比", value: 3 },
              { label: "定性质控", value: 4 },
          ],
          reqsourceOptions: [
              { label: "读取外部系统申请单", value: "0" },
              { label: "LIS门诊采血生成", value: "1" },
              { label: "病区护士站生成", value: "3" },
              { label: "住院医生站生成", value: "4" },
              { label: "标本拆分之后的标本", value: "5" },
              { label: "为院感系统生产", value: "6" },
              { label: "输入病历号开窗选取项目后生成", value: "21" },
              { label: "Lis系统登记生成", value: "22" },
              { label: "通过检验中心登记", value: "23" },
              { label: "外院标本", value: "24" },
              { label: "POCT生成的申请单", value: "25" },
              { label: "报告处理界面录入的申请", value: "26" },
              { label: "住院医生站输血申请", value: "41" },
              { label: "输血申请附带的检验申请", value: "42" },
          ],
          //设定Grid窗口 按回车键跳到下一列
          keyConfig: {
              isArrow: true,
              isDel: true,
              isTab: true,
              isEdit: true,
              editMethod: ({ seq, row, rowIndex, column, columnIndex, cell }) => {},
          },

          //以下为分割条和窗口界面布局参数
          leftwidth: 0,
          rightwidth: 450,
          topheight: 30,
          bottomheight: 0,
      };
  },
  computed: {},
  //html加载完成之前，执行。执行顺序：父组件-子组件
  created() {
      this.targetSetBegindt = new Date();
  },
  //.html加载完成后执行。执行顺序：子组件-父组件
  mounted() {},
  updated() {}, //数据变化时加载事件
  watch: {
      instrId(val) {
          this.initialList();
      },
  },
  methods: {
      //按value返回对应的label值
      getSelectLabel(value, list, valueProp = "value", labelField = "label") {
          for (let index in list) {
              if (list[index].value == value) {
                  return list[index].label;
              }
          }
          return null;
      },

      //查询左边list
      labinstrumentchange(id, name) {
          this.instrId = id;
          this.instrName = name;
          this.initialList();
      },

      //初始化数据
      resetData() {
          this.tableData1 = [];
          this.tableData2 = [];
          this.tableData3 = [];
          // this.qcsForm = {};
          // this.qcsDisplay = {};
      },
      //以下为质控录入判断

      //打开窗时初始化
      initialList() {
          this.loading = true;
          this.resetData();
          this.getDataByAjax(
              {
                  url: "LIS/LIS5/LIS514",
                  method: "post",
                  data: {
                      action: "getRptitemList",
                      instrid: this.instrId, //查询条件：仪器
                  },
              },
              "",
              "",
              (data) => {
                  this.tableData1 = data;
                  this.loadFirstRow(this.$refs.xTable1, ""); //回调函数未完善，有时出错，用下面的$nextTick
                  this.$nextTick(() => {
                      var currentRow = this.$refs.xTable1.getCurrentRow();
                      if (currentRow) {
                          this.rpt_itemcode = currentRow.rpt_itemcode;
                          this.detailRetrieve(this.rpt_itemcode);
                      } else {
                          this.rpt_itemcode = "";
                      }
                  });
              },
              (data) => {
                  //errFunction
              }
          );
          this.loading = false;
      },

      //左边list窗口行变换事件
      masterRowChangedEvent({ row }) {
          this.masterRowChanged(row);
      },
      //左边list行变换执行
      masterRowChanged(row) {
          this.rpt_itemcode = row.rpt_itemcode; //给右边Tab显示用的数据
          this.detailRetrieve(this.rpt_itemcode);
      },

      // 增加 按钮触发
      BtnAdd() {
          if (this.instrId == 0) {
              this.$message("请选择仪器");
              return false;
          }
          let msg = this.valid(this.rpt_itemcode, "请选择左边的项目");
          if (msg) return msg;
          var row = {};
          row.qcruletype = 1;
          row.begindt = XEUtils.toStringDate(XEUtils.toDateString(new Date(), "yyyy-MM-dd"));
          row.qcrule = "1_3S,2_2S,R4S,4_1S,10X";
          this.insertRowAtLast(this.$refs.xTable2, row);
      },

      // 修改按钮触发
      BtnSave() {
          if (this.instrId == 0) {
              this.$message("请选择仪器");
              return false;
          }
          let msg = this.valid(this.rpt_itemcode, "请选择左边的项目");
          if (msg) return msg;
          //校验 数据
          var record = this.$refs.xTable2.tableData;
          for (let i = 0, len = record.length; i < len; i++) {
              let msg;
              msg = this.valid(record[i].qcruletype, "第" + (i + 1) + "行 规则大类 必须填写！");
              if (msg) return msg;
              msg = this.valid(record[i].begindt, "第" + (i + 1) + "行 启用日期 必须填写！");
              if (msg) return msg;
          }
          let xTabledata = this.$refs.xTable2.getRecordset();
          this.getDataByAjax(
              {
                  url: "LIS/LIS5/LIS513",
                  method: "post",
                  data: {
                      action: "save",
                      instrId: this.instrId,
                      urec: xTabledata,
                      ruleType: this.rpt_itemcode,
                  },
              },
              "操作成功！",
              "保存失败！",
              (data) => {
                  //okFunction
                  this.initialList();
              },
              (data) => {
                  //errFunction
              }
          );
      },

      //删除按钮触发
      BtnDel() {
          this.deleteRow(this.$refs.xTable2);
      },

      //右边 Tab 明细窗口刷新数据
      detailRetrieve(rpt_itemcode) {
          this.tableData2 = [];
          this.$tool
              .request({
                  url: "LIS/LIS5/LIS513",
                  method: "post",
                  data: {
                      action: "query",
                      instrid: this.instrId,
                      ruleType: rpt_itemcode,
                  },
              })
              .then((response) => {
                  this.tableData2 = response.Data;
              })
              .catch((e) => {});
      },

      //打开质控规则选择窗口
      openRule({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, cell }) {
          if (row) this.$refs.xTable2.setCurrentRow(row);
          else this.$refs.xTable2.setCurrentRow(null);
          var rule = row.qcrule;
          var rulearr = rule.split(",");
          this.qcruleDialogVisible = true;
          this.$tool
              .request({
                  url: "LIS/LIS5/LIS513",
                  method: "post",
                  data: {
                      action: "getQcrule",
                  },
              })
              .then((response) => {
                  this.tableData3 = response.Data;
                  if (rulearr.length > 0) {
                      for (let i = 0; i < rulearr.length; i++) {
                          var selrow = this.tableData3.filter((item) => item.qcrule == rulearr[i]);
                          if (selrow.length > 0) {
                              this.$refs.xTable3.setSelection(selrow[0], true);
                          }
                      }
                  }
              });
      },

      //弹窗选择质控规则后 确认按钮
      ruleOk() {
          var selectRows = this.$refs.xTable3.getSelectRecords();
          if (selectRows) {
              var qcrule = "";
              for (let index in selectRows) {
                  qcrule += "," + selectRows[index].qcrule;
              }
              if (qcrule.trim().length > 0) {
                  qcrule = qcrule.substring(1);
              } else {
                  qcrule = "";
              }
          } else {
              return;
          }
          var currentRow = this.$refs.xTable2.getCurrentRow();
          currentRow.qcrule = qcrule;
          this.qcruleDialogVisible = false;
      },

      //弹窗选择质控规则后 关闭按钮
      ruleClose() {
          this.qcruleDialogVisible = false;
      },

      ///////////////////////////////////工具函数 /////////////////////////////////////////
      getDataByAjax(
          request,
          okMsg,
          errMsg,
          okFunction, // 取得数据后的回调函数
          errFunction // 获取数据失败后回调函数
      ) {
          this.$tool.request(request).then((response) => {
              if (response.errcode == "1") {
                  if (XEUtils.isString(okMsg)) {
                      if (XEUtils.getSize(XEUtils.trim(okMsg)) > 0) {
                          this.$message({
                              message: okMsg,
                              type: "success",
                          });
                      }
                  }
                  if (typeof okFunction == "function") okFunction(response.Data);
              } else {
                  this.$message({
                      dangerouslyUseHTMLString: true,
                      message: errMsg + "<br><br>详细信息：" + response.errmsg,
                      type: "warning",
                  });
                  if (typeof errFunction == "function") errFunction(response.Data);
              }
          });
      },

      insertRowAtLast(xtable, row) {
          xtable.insertAt(row, -1); //在最后添加一行
          var curow = xtable.getTableData().fullData[xtable.getTableData().fullData.length - 1]; //获取 新加的行对象 row 数据集合
          xtable.setCurrentRow(curow); //高亮显示行
          this.$nextTick(() => {
              xtable.scrollToRow(curow); //待数据加载完成后，延迟 滚动 到行
          });
      },

      //自动加载表格的第一行，并执行回调函数
      loadFirstRow(xTable, func) {
          this.$nextTick(() => {
              // 加载第一行
              var selectrow = xTable.getData(0);
              if (selectrow) {
                  xTable.setCurrentRow(selectrow); //高亮行
                  xTable.scrollToRow(selectrow); //滚动到行
                  if (typeof func == "function") func(selectrow);
              } else {
                  xTable.setCurrentRow(null); //这个不会自动清空
              }
          });
      },

      //自制必填校验函数，以后待扩展
      valid(obj, message) {
          if (XEUtils.isUndefined(obj)) {
              return this.$message({
                  message: message,
                  type: "warning",
              });
          }
          if (XEUtils.isNull(obj)) {
              return this.$message({
                  message: message,
                  type: "warning",
              });
          }
          if (XEUtils.isString(obj)) {
              if (!XEUtils.getSize(obj) > 0) {
                  return this.$message({
                      message: message,
                      type: "warning",
                  });
              }
          }
          if (XEUtils.isDate(obj)) {
              if (obj < XEUtils.toStringDate("2000-01-01")) {
                  return this.$message({
                      message: message,
                      type: "warning",
                  });
              }
          }
      },

      //删除表格行工具//TODO 连续 点删除按钮会有失去焦点的问题待解决
      deleteRow(xTable) {
          var delrow = xTable.getCurrentRow();
          if (delrow) {
              this.DelIndex = xTable.getRowIndex(delrow);
              xTable.remove(delrow);
              if (this._this.DelIndex > -1 && xTable.tableData.length > 0) {
                  if (xTable.getTableData().fullData.length > this.DelIndex) this.DelIndex = this.DelIndex;
                  else this.DelIndex = this.DelIndex - 1;
                  var selectrow = xTable.getTableData().fullData[this._this.DelIndex];
                  this.$nextTick(() => {
                      xTable.setCurrentRow(selectrow);
                  });
              } else {
                  var nowdata = xTable.getTableData().fullData.filter((item) => {
                      return item._XID < delrow._XID;
                  });
                  if (nowdata.length > 0) {
                      var selectrow = nowdata[nowdata.length - 1];
                      this.$nextTick(() => {
                          xTable.setCurrentRow(selectrow);
                      });
                  }
              }
          }
      },

      stddevp(numbers) {
          var mean = 0;
          var sum = 0;
          var avgValue, sdValue, cvValue;
          for (var i = 0; i < numbers.length; i++) {
              sum += Number(numbers[i]);
          }
          mean = sum / numbers.length;
          avgValue = mean;

          sum = 0;
          for (var i = 0; i < numbers.length; i++) {
              sum += Math.pow(numbers[i] - mean, 2);
          }
          sdValue = Math.sqrt(sum / numbers.length);

          if (avgValue != 0) {
              cvValue = (sdValue * 100) / avgValue;
          } else {
              cvValue = null;
          }
          return {
              avgValue: XEUtils.toFixedString(mean, 2),
              sdValue: XEUtils.toFixedString(sdValue, 2),
              cvValue: XEUtils.toFixedString(cvValue, 2),
          };
      },

      //以下为分割条控件，指定函数
      yleftmousedown(ev) {
          let that = this;
          let el = ev.target;
          var disX = ev.clientX - el.offsetLeft;
          document.onmousemove = function (ev) {
              var l = ev.clientX - disX;
              if (l < 20) l = 20;
              that.rightwidth = l;
          };
          document.onmouseup = function () {
              document.onmousemove = null;
              document.onmouseup = null;
          };
      },
      yrightmousedown(ev) {
          let that = this;
          let el = ev.target;
          var disX = ev.clientX - el.offsetLeft;
          document.onmousemove = function (ev) {
              var l = ev.clientX - disX;
              let rw = el.parentElement.clientWidth - l;
              if (rw < 20) rw = 20;
              that.leftwidth = rw;
          };
          document.onmouseup = function () {
              document.onmousemove = null;
              document.onmouseup = null;
          };
      },
      xtopmousedown(ev) {
          let that = this;
          let el = ev.target;
          var disY = ev.clientY - el.offsetTop;
          document.onmousemove = function (ev) {
              var l = ev.clientY - disY;
              if (l < 20) l = 20;
              that.topheight = l;
          };
          document.onmouseup = function () {
              document.onmousemove = null;
              document.onmouseup = null;
          };
      },
      xbottommousedown(ev) {
          let that = this;
          let el = ev.target;
          var disY = ev.clientY - el.offsetTop;
          document.onmousemove = function (ev) {
              var l = ev.clientY - disY;
              let bh = el.parentElement.clientHeight - l;
              if (bh < 20) bh = 20;
              that.bottomheight = bh;
          };
          document.onmouseup = function () {
              document.onmousemove = null;
              document.onmouseup = null;
          };
      },
      //关闭按钮
      BtnExc() {
          let index = this.$parent.$refs.itemtags.tagsList.findIndex((m) => m.name == "LIS514");
          this.$parent.$refs.itemtags.tagsList.splice(index, 1);
          this.$router.go(-1);
      },
  },
  beforeRouteEnter(to, from, next) {
      next((vm) => {
          let that = vm;
          let altArr = [];
          document.onkeydown = function (e) {
              let key = window.event.keyCode;
              console.log("key=", key);
              //*组合按键
              if (altArr.length > 0) {
                  //65到90 a到z（A到Z）
                  // //*Alt + C 清除
                  // if (key == 67) {
                  //     this.BtnExc();
                  // }
                  //*Alt + E 退出
                  if (key == 69) {
                      that.BtnExc();
                  }
              } else {
                  if (key == 119) {
                      //F8
                      that.initialList();
                  } else if (key == 113) {
                      //F2
                      var e = [];
                      e.shiftKey = false;
                      that.BtnAdd(e);
                  } else if (key == 114) {
                      //F3
                      that.BtnDel();
                  } else if (key == 117) {
                      //F6
                      that.BtnSave();
                  } else if (key == 18) {
                      console.log("按下'ALT'");
                      //按下了alt
                      altArr.push(key);
                  }
              }
          };
          document.onkeyup = function (e) {
              let key = window.event.keyCode;
              if (key == 18) {
                  altArr = [];
              }
          };
      });
  },
};
</script>

<style scoped>
.pagetop {
  width: 100%;
  height: 70px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: 1px solid #ccc;
  position: absolute;
}

.pagecenter {
  position: absolute;
  width: 100%;
  left: 0;
  top: 75px;
  border: 0px solid #ccc;
  overflow: auto;
}

.pagebottom {
  width: 100%;
  bottom: 0px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: 1px solid #ccc;
  position: absolute;
}

.middle-left {
  position: absolute;
  height: 100%;
  left: 0px;
  overflow: auto;
  background-color: aqua;
}

.middle-right {
  position: absolute;
  height: 100%;
  right: 0px;
  bottom: 0px;
  overflow: visible;
}
.middle-center {
  position: absolute;
  height: 100%;
  overflow: auto;
}
.ysplit {
  height: 100%;
  width: 5px;
  position: absolute;
  z-index: 99;
  cursor: col-resize;
}
.xsplit {
  width: 100%;
  height: 5px;
  position: absolute;
  z-index: 99;
  cursor: row-resize;
}

table tr td:nth-child(odd) {
  text-align: right;
  white-space: nowrap;
  font-size: 12px;
  font-weight: 700;
}
table tr td:nth-child(even) {
  text-align: left;
}

table tr td:nth-child(1) {
  width: 80px;
}

.showDataTable {
  font-size: 12px;
}

.showDataTable tr td {
  padding: 5px 0px 5px 0px;
}
</style>
